package com.cnsunrun.commonui.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;


public final class FileUtils {

    /**
     * 检查SD卡
     *
     * @return
     */
    public static boolean checkSDcard() {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }

    /**
     * 获取缓存目录
     *
     * @return
     */
    public static String getCacheFile(Context context) {
        if (checkSDcard()) {
            return context.getExternalCacheDir().getAbsolutePath() + File.separator;
        } else {
            return context.getCacheDir().getAbsolutePath() + File.separator;
        }
    }


    /**
     * 保存文件
     *
     * @param folderPath
     * @param fileNmae
     * @return
     */
    public static File getSaveFile(String folderPath, String fileNmae) {
        File file = new File(getSavePath(folderPath) + File.separator
                + fileNmae);
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    public static String getSavePath(String folderName) {
        return getSaveFolder(folderName).getAbsolutePath();
    }


    public static File getSaveFolder(String folderName) {
        File file = new File(Environment.getExternalStorageDirectory()
                .getAbsoluteFile()
                + File.separator
                + folderName
                + File.separator);
        file.mkdirs();
        return file;
    }

    /**
     * 获取数据保存目录
     *
     * @param context
     * @return
     */
    public static String getDBPath(Context context) {
        if (!checkSDcard()) {// 如果不存在
            LogUtils.e("SD卡管理:", "SD卡不存在,请加载SD卡");
            return null;
        } else {// 如果存在
            // 数据库所在目录
            return Environment.getExternalStorageDirectory().getAbsolutePath()
                    + File.separator
                    + context.getPackageName()
                    + File.separator
                    + "db";
        }
    }


    /**
     * 追加写入字符串为文件
     *
     * @param str
     */
    public static void writeAppendStrToFile(Context context, String str) {
        try {
            String     allData = getCacheFile(context) + File.separator + TimeUtils.timeStampToDate(System.currentTimeMillis(), "yyyy-MM-dd每日闹钟更新数据") + ".txt";
            FileWriter fw      = new FileWriter(allData, true);
            fw.flush();
            fw.write(str);
            fw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 写入字符串为文件
     *
     * @param str
     */
    public static void writeStrToFile(Context context, String str) {
        try {
            FileWriter fw = new FileWriter(getCacheFile(context) + File.separator +
                    TimeUtils.timeStampToDate(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss") + ".txt");//SD卡中的路径
            fw.flush();
            fw.write(str);
            fw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据路径获得图片并压缩，返回bitmap用于显示
     *
     * @param filePath
     * @return
     */
    public static Bitmap getSmallBitmap(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 480, 800);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeFile(filePath, options);
    }

    /**
     * 计算图片的缩放值
     *
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height       = options.outHeight;
        final int width        = options.outWidth;
        int       inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio  = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    /**
     * 把bitmap转换成base64
     *
     * @return
     */
    public static String bitmapToBase64(String filePath) {
        Bitmap                bm   = getSmallBitmap(filePath);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //1.5M的压缩后在100Kb以内，测试得值,压缩后的大小=94486字节,压缩后的大小=74473字节
        //这里的JPEG 如果换成PNG，那么压缩的就有600kB这样
        bm.compress(Bitmap.CompressFormat.JPEG, 40, baos);
        byte[] b = baos.toByteArray();
        LogUtils.e("FileUtils", "压缩后的大小：" + b.length);
        return "data:image/jpeg;base64," + Base64.encodeToString(b, Base64.NO_WRAP);
    }

}